package services

import (
	"Bok/daos"
	"Bok/models"
	"Bok/utils"
	"errors"
	"fmt"
	"time"
)

type UserService interface {
	LoginService(loginInfo models.LoginInfo) (*models.LoginBack, error)
	EditService(userId uint, editInfo models.EditUserRequest) (map[string]interface{}, error)
}

type userService struct {
	userDao daos.UserDao
}

func NewUserService(userDao daos.UserDao) UserService {
	return &userService{userDao: userDao}
}
func (u *userService) LoginService(loginInfo models.LoginInfo) (*models.LoginBack, error) {
	password := loginInfo.Password
	// 将密码加密
	loginInfo.Password, _ = utils.HashPassword(loginInfo.Password)
	// 接下来查看数据库里面有没有(请求 dao层)

	data, err := u.userDao.LoginDao(&loginInfo)

	if err != nil {
		fmt.Println("1")
		return nil, err
	}
	if data == nil {
		fmt.Println("2")
		return nil, errors.New("没有此用户，data 为空")
	}
	if !utils.CheckPasswordHash(password, data.Password) {
		fmt.Println("3")
		return nil, errors.New("密码不正确")
	}
	// 密码验证成功，需要添加token
	expireTime := time.Now().Add(7 * 24 * time.Hour)

	token, effectiveTime, err := utils.GenerateToken(data.Id, data.Username, data.LoginId, expireTime)
	if err != nil {
		fmt.Println("4")
		return nil, errors.New("token生成失败")
	}

	// 转换为秒级时间戳
	expireTimestamp := effectiveTime.Unix() // 返回int64类型，单位：秒
	// 返回的数据
	ret := models.LoginBack{
		UserInfoBase: models.UserInfoBase{Username: loginInfo.Username},
		LoginId:      loginInfo.LoginId,
		Token:        token,
		ExpireTime:   expireTimestamp,
	}
	fmt.Println("返回的数据:", ret)
	return &ret, nil
}

func (s userService) EditService(userId uint, req models.EditUserRequest) (map[string]interface{}, error) {
	data, err := s.userDao.GetUserById(userId)
	if err != nil {
		return nil, err
	}
	// 构造新数据
	var newUserInfo = make(map[string]interface{})
	if req.Username != nil {
		newUserInfo["username"] = *req.Username
	}
	if req.Email != nil {
		newUserInfo["email"] = *req.Email
	}
	if req.NewPassword != nil {
		newUserInfo["password"], _ = utils.HashPassword(*req.NewPassword)
	}
	if req.Bio != nil {
		newUserInfo["bio"] = *req.Bio
	}
	if req.AvatarURL != nil {
		newUserInfo["avatar_url"] = *req.AvatarURL
	}
	if req.DisplayName != nil {
		newUserInfo["display_name"] = *req.DisplayName
	}

	// 传给 dao 层
	if err := s.userDao.UpdateUser(userId, newUserInfo); err != nil {
		return nil, err
	}
	newUserInfo["username"] = data.Username
	return newUserInfo, nil
}
